package com.ttsx.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.ttsx.core.common.constant.AlipayConstants;
import com.ttsx.core.common.result.Result;
import com.ttsx.pojo.dto.payment.PaymentQueryDTO;
import com.ttsx.pojo.entity.Order;
import com.ttsx.service.OrderService;
import com.ttsx.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wb
 * @since 2025-11-07
 */

@Slf4j
@RestController
@RequestMapping("/pay")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private OrderService orderService;


    @PostMapping("page/{pIndex}/{pSize}")
    public Result<?> pageOrder(
            @PathVariable("pIndex") Integer pIndex,
            @PathVariable("pSize") Integer pSize,
            @RequestBody PaymentQueryDTO paymentQueryDTO) {
        return Result.success(paymentService.getPage(pIndex, pSize, paymentQueryDTO));
    }

    @GetMapping("{orderId}")
    public Result<?> pay(@PathVariable("orderId") Long orderId){
        Order order = orderService.getById(orderId);
        AlipayTradePagePayResponse response = paymentService.createPay(order, order.getPayMethod());
        return Result.success(response.getBody());
    }



    @RequestMapping("/callback")
    public void callback(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, IOException {

        // 获取回调参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        log.info("回调参数：{}", parameterMap);


        // 封装参数
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            if (values != null && values.length > 0) {
                params.put(name, values[0]);
                // 乱码处理
                //params.put(name, new String(values[0].getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
            }
        }

        // 验签
        boolean b = AlipaySignature.rsaCheckV1(params, AlipayConstants.PUBLIC_KEY, AlipayConstants.CHARSET, AlipayConstants.SIGN_TYPE);

        if(b){
            log.info("回调验签成功");

            String tradeStatus = params.get("trade_status");
            String outTradeNo = params.get("out_trade_no");

            if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                log.info("支付成功 商户订单号{} 交易订单号->{}", outTradeNo, params.get("trade_no"));
                // 支付成功，更新订单状态
                paymentService.updateStatus(outTradeNo, params.get("trade_no"));
            }

            // 通知支付宝回调处理成功
            response.getWriter().write("success");
        }else{
            log.info("回调验签失败");
            response.getWriter().write("fail");
        }
    }

}
